package cn.aimer.hrm.service.impl;

import cn.aimer.hrm.client.LoginUserClient;
import cn.aimer.hrm.domain.Employee;
import cn.aimer.hrm.domain.LoginUser;
import cn.aimer.hrm.domain.Tenant;
import cn.aimer.hrm.dto.TenantEnteringDto;
import cn.aimer.hrm.exception.ErrorCode;
import cn.aimer.hrm.exception.ValidUtil;
import cn.aimer.hrm.mapper.EmployeeMapper;
import cn.aimer.hrm.mapper.TenantMapper;
import cn.aimer.hrm.query.TenantQuery;
import cn.aimer.hrm.service.ITenantService;
import cn.aimer.hrm.util.AjaxResult;
import cn.aimer.hrm.util.PageList;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aimer
 * @since 2022-01-02
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginUserClient loginUserClient;
    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {

        // 封装page对象
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());
        // 查询当前页数据
        List<Tenant> datas = tenantMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),datas);
    }

    @Override
    public void entering(TenantEnteringDto enteringDto) {
        //  1 参数校验
        // 1.1 null检验
        // 1）直接使用异常类
        // if (enteringDto.getMealId()==null)
        //   throw new GlobalException("请选择套餐后再操作！");
        // 2)使用断言
        //  ValidUtil.assertNotNull(enteringDto.getMealId(),ErrorCode.CODE_400_MEAL_NOT_NULL);
        // 1.2 判断租户是否已经存在
        EntityWrapper<Tenant> wrapper = new EntityWrapper<>();
        Tenant tenant = enteringDto.getTenant();
        wrapper.eq("company_name", tenant.getCompanyName());
        List<Tenant> list = tenantMapper.selectList(wrapper);
        /*if (list!=null && list.size()>0)
            throw new GlobalException("租户已经入驻！直接登录");*/
        ValidUtil.assertListIsNull(list, ErrorCode.CODE_400_TENANT_EXSIT);
        // 1.3 管理员已经存在  方案1（采纳）：让他直接登录进去添加机构 方案2：进行密码比对，直接关联即可。
        Employee employee = enteringDto.getEmployee();
        List<Employee> es = employeeMapper.selectList(new EntityWrapper<Employee>()
                .eq("username", employee.getUsername())
                .or()
                .eq("email", employee.getEmail())
                .or()
                .eq("tel", employee.getTel())
        );
        /*if (es!=null &&  es.size()>0)
            throw new GlobalException("您已经入驻过店铺了！登录后可以添加新的店铺！");*/
        ValidUtil.assertListIsNull(es,ErrorCode.CODE_400_ADMIN_EXSIT);
        // 2 调用授权服务里面登录用户服务添加用户，并返回登录id
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setEmail(employee.getEmail());
        loginUser.setPhone(employee.getTel());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String enPass = bCryptPasswordEncoder.encode(employee.getPassword());
        loginUser.setPassword(enPass);
        loginUser.setType(0);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        /*if (!ajaxResult.isSuccess())
            throw new RuntimeException(ajaxResult.getMessage());*/
        ValidUtil.assertTrue(ajaxResult.isSuccess(),ajaxResult.getMessage());

        Long loginUserId = Long.valueOf(ajaxResult.getResultObj().toString());
        // 3 添加管理员
        employee.setLoginId(loginUserId);
        employee.setPassword(enPass);
        employeeMapper.insert(employee);
        // 4 添加租户
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);
        // 5 租户与套餐直接中间表
        Map<String,Long> params = new HashMap<>();
        params.put("tenantId",tenant.getId());
        params.put("mealId",enteringDto.getMealId());
        tenantMapper.saveTenatMeals(params);
    }
}
